package com.itsu.app.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import com.itsu.commons.annotations.MyCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
public class CacheInterceptor implements HandlerInterceptor {

    @Autowired
    RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)){
            return true;
        }

        if (!((HandlerMethod) handler).hasMethodAnnotation(GetMapping.class)) {
            return true;
        }

        if (!((HandlerMethod) handler).hasMethodAnnotation(MyCache.class)) {
            return true;
        }

        // 从Redis中获取缓存数据
        String cacheData = redisTemplate.opsForValue().get(getCacheKey(request));
        if (StrUtil.isBlank(cacheData)) {
            // 该请求还没有缓存 直接放行
            return true;
        }

        System.out.println("数据是从缓存中取走了....");

        response.setContentType("application/json;charset=utf-8");
        response.getWriter().println(cacheData);
        return false;
    }

    public static String getCacheKey(HttpServletRequest request) {
        // 获取请求地址
        String requestURI = request.getRequestURI();
        // 获取请求参数
        Map<String, String[]> map = request.getParameterMap();
        // 获取请求的Token
        String token = request.getHeader("token");
        return SecureUtil.md5(requestURI + "_" + JSONUtil.toJsonStr(map) + "_" + token);
    }
}
